<template>
  <div>
    <head-top title="联系人列表"></head-top>
    <div class="container">
      <van-address-list
        v-model="whichAddressId"
        :list="list"
        default-tag-text="默认"
        @add="goAddContact"
        @edit="goChangeContact"
        @select="clickContact"
      />
    </div>
  </div>
</template>

<script>
import HeadTop from '../../components/headtop.vue'
import { getContacts } from '_api'
import { getToken } from '_utils/token.js'
export default {
  components: { HeadTop },
  data () {
    return {
      whichAddressId: '',
      list: []
    }
  },
  created () {
    this.getContacts()
  },
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('path', from.path)
    next()
  },
  methods: {
    getContacts () {
      getContacts({
        token: getToken()
      }).then((res) => {
        if (res.data.code === 0) {
          const oldcontacts = res.data.data.result
          const newcontacts = []
          oldcontacts.forEach((oldcontacts) => {
            const address = {}
            for (const key in oldcontacts) {
              if (key === 'linkMan') {
                address.name = oldcontacts[key]
              } else if (key === 'mobile') {
                address.tel = oldcontacts[key]
              } else {
                address[key] = oldcontacts[key]
              }
            }
            newcontacts.push(address)
          })
          this.list = newcontacts
          const defaultone = newcontacts.find((item) => item.isDefault)
          if (defaultone) {
            this.whichAddressId = defaultone.id
          } else {
            this.whichAddressId = newcontacts[0].id
          }
        }
      })
    },
    goAddContact () {
      this.$router.push('/contactsAdd')
    },
    goChangeContact (msg) {
      this.$router.push({
        path: '/contactsUpdate',
        query: {
          contactId: msg.id
        }
      })
    },
    clickContact (contact) {
      const path = localStorage.getItem('path')
      if (path === '/order') {
        this.$router.replace({
          path: '/order',
          query: {
            contactId: contact.id
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .container {
  padding-top: 0.9rem;
  .van-address-list__bottom {
    padding: 0 0.05rem;
    .van-button--round {
      border-radius: 0;
    }
  }
}
/deep/ .van-address-item {
  border-radius: 0 !important;
  border-bottom: 1px solid #aaabac !important;
}
</style>
